package cn.heycm.blog.console.api;

import cn.heycm.blog.api.console.paramcfg.ParamCfgApi;
import cn.heycm.blog.api.console.paramcfg.command.SaveCfgCmd;
import cn.heycm.blog.api.console.paramcfg.query.CfgQry;
import cn.heycm.blog.api.console.paramcfg.vo.CfgVO;
import cn.heycm.blog.common.entity.page.Page;
import cn.heycm.blog.common.entity.result.CodeMsg;
import cn.heycm.blog.common.entity.result.Result;
import cn.heycm.blog.common.mybatis.PageUtil;
import cn.heycm.blog.console.infra.convert.ConsoleConvert;
import cn.heycm.blog.console.domain.paramcfg.ParamCfgRepository;
import cn.heycm.blog.console.infra.dao.paramcfg.entity.ParamCfg;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hey
 * @version 1.0
 * @since 2024/9/19 15:55
 */
@RestController
@AllArgsConstructor
public class ParamCfgApiImpl implements ParamCfgApi {

    private final ParamCfgRepository repository;

    @Override
    public Result<Object> save(SaveCfgCmd cmd) {
        ParamCfg paramCfg = ConsoleConvert.INST.toEntity(cmd);
        repository.save(paramCfg);
        return Result.success();
    }

    @Override
    public Result<Page<CfgVO>> page(CfgQry qry) {
        Page<ParamCfg> page = repository.page(qry.getPage(), qry.getSize(), qry.getKeyword());
        return Result.success(PageUtil.convert(page, ConsoleConvert.INST::toVO));
    }

    @Override
    public Result<CfgVO> find(String alias) {
        ParamCfg cfg = repository.find(alias);
        return null == cfg ? Result.error(CodeMsg.CFG_NOT_EXISTS) : Result.success(ConsoleConvert.INST.toVO(cfg));
    }
}
